<template>
  <div id="poster">

    <el-form 
    class="login-container"
    :model="loginForm" 
    status-icon
    :rules="loginFormRules"
    ref="loginFormRef"
     >
      <h3 class="login_title">后台登录</h3>
      <el-form-item prop="username">
        <el-input
          type="text"
          v-model="loginForm.username"
          auto-complete="off"
          placeholder="账号"
          prefix-icon="el-icon-user"
        ></el-input>
      </el-form-item>

      <el-form-item prop="password">
        <el-input
          type="password"
          v-model="loginForm.password"
          auto-complete="off"
          placeholder="密码"
          prefix-icon="el-icon-lock"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <Captcha></Captcha>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          @click="login"
          auto-complete="off"
          class="login_button"
          :disabled="dataItem.button_disabled"
          v-loading="loading"
          >登录</el-button
        >
      </el-form-item>
    <div class="rot">
      <router-link class="forgot_pass" to="/">忘记密码?</router-link>
      <router-link type="primary" class="registe" to="/register">注册</router-link>
    </div>
    </el-form>

  </div>
</template>

<script>
import { login } from "../api/interface";
import { mapMutations } from "vuex";
import router from "../router/index";
import QS from "qs";
import Captcha from "../components/Captcha";
import { h } from 'vue';
export default {
  //导入验证组件
  components: { Captcha },
  data() {
    const checkUsername = (rule, value, callback) => {
      //用户名正则
      const regUsername = /^[a-zA-Z0-9]{8,16}$/;
      if(!value){
        return callback(new Error("请输入账号"))
      }
      if(!regUsername.test(value)){
        return callback(new Error("账号为8-16位数字或字母"))
      }
      if(regUsername.test(value)){
        return callback();
      }
    }

    const checkPassword = (rule, value, callback) => {
      const regPassword = /^[a-zA-Z0-9]{8,20}$/;
      if(!value){
        return callback(new Error("请输入密码"))
      }
      if(!regPassword.test(value)){
        return callback(new Error("密码为8-20位数字或字母"))
      }
      if(regPassword.test(value)){
        return callback();
      }
    }

    return {
      loginForm: {
        username: "",
        password: "",
      },
      loginFormRules: {
        username: [
          { required: true, message: "请输入账号",trigger: "change" },
          { validator: checkUsername, trigger: "change" }
        ],
        password: [
          { required: true, message: "请输入密码",trigger: "change" },
          { required: checkPassword, trigger: "change" }
        ]
      },
      dataItem: {
        button_disabled: false,
        sec: 60*10,
        timer: null,
      },
      loading: false,
    };
  },
  methods: {

    // 登录预验证
    ...mapMutations(["setToken"]),
    login() {
      this.$refs.loginFormRef.validate(async (valid) => {
        if(!valid){
          //3秒后清除提示的错误信息
          setTimeout(() => {
            this.$refs.loginFormRef.clearValidate();
          }, 3000);
          return;
        }
        
        const result = await login(QS.stringify(this.loginForm));
        const loginUsername = this.loginForm.username;
        console.log(result);
          //成功
          if (result.code == 205) {
            this.setToken({ token: result.data });
            const loading = this.$loading({
              lock: true,
              text: '登陆中...请稍等',
              spinner: 'el-icon-loading',
              background: 'rgba(220 220 220)'
            });
            setTimeout(() => {
              loading.close();
              this.$message.success("登陆成功");
              router.push("/Home");
            }, 2000);
            
          }
          if(result.code == 405){
            this.loading = true;
            setTimeout(() => {
              this.$message.error("账号或密码错误")
              this.loading = false;
            }, 2000);
            router.push("/Login");
          }
          //禁用
          if(result.data === "用户【"+loginUsername+"】已被禁用"){
            this.loading = true;
            setTimeout(() => {
              this.$notify({
              title: '登陆异常',
              message: h(
                  "i",
                  { style: "color: orange" },
                  '账号【'+loginUsername+'】已被禁用，请联系管理员解除',
                ),
              type: "warning",
              position: 'top-left'
            });
              this.loading = false;
            }, 2000);
            
          }
          //不存在
          if(result.data === "用户【"+loginUsername+"】不存在"){
            this.loading = true;
            setTimeout(() => {
              this.$notify({
              title: '登陆失败',
              message: h(
                  "i",
                  { style: "color: red" },
                  '账号【'+loginUsername+'】不存在，请重新输入',
                ),
              type: "error",
              position: 'top-left'
            });
              this.loading = false;
            }, 2000);
          }
          //锁定
          if(result.data === "用户【" + loginUsername + "】已被锁定，请【" + 10 +"】分钟后再尝试登录"){
            
            this.loading = true;
            setTimeout(() => {
              this.$notify({
              title: '登陆失败',
              message: h(
                  "i",
                  { style: "color: red" },
                  '由于您多次登录失败，账号【'+loginUsername+'】已被锁定，请10分钟后再尝试登陆',
                ),
              type: "warning",
              position: 'top-left'
            });
              this.loading = false;
            }, 2000);
            //计时器
            if (this.dataItem.timer) {
              //计时器存在就清除计时器
              clearInterval(this.dataItem.timer);
            }
            this.dataItem.timer = setInterval(() => {
            const se = this.dataItem.sec--;
            this.dataItem.button_disabled = true;
            if (se <= 0) {
              clearInterval(this.dataItem.timer);
              this.dataItem.button_disabled = false;
            }
          }, 1000);
          history.replaceState(this.dataItem.timer,"计时器");
          }

      })
    },
  },
  created() {
    this.dataItem.timer = history.state;
  },
};
</script>

<style lang="less" scoped>
#poster{
    background: url("../assets/bg1.jpg") no-repeat;
    background-position: center;
    height: 100%;
    width: 100%;
    background-size: cover;
    position: fixed;
    margin: 0px;
    padding: 0px;
    .forgot_pass{
      text-decoration:none;
      font-size: 15px;
      color: red;
      padding: 0px 40px 0px 50px;
    }
    .registe{
      text-decoration:none;
      font-size: 15px;
      color: red;
      padding: 0px 80px 0px 80px;
    }
}
.login-container {
  border-radius: 15px;
  background-clip: padding-box;
  margin: 250px auto;
  height: 350px;
  width: 350px;
  padding: 35px 35px 15px 35px;
  background: #fff;
  border: 1px solid #eaeaea;
  box-shadow: 0 0 25px #cac6c6;
}
.login_title {
  margin: 0px auto 40px auto;
  text-align: center;
  color: #505458;
}
.login_button {
  width: 100%;
  background-color: #505458;
  border: none;
}

</style>